<?php

namespace app\service;

use app\admin\model\Config;
use app\model\AdminAgent;
use app\model\AgentDistribution;
use app\model\AgentShop;
use app\model\DistributionSetting;
use app\model\Goods;
use app\model\GoodsFree;
use app\model\Order;
use app\model\OrderTeamCommissionLogModel;
use app\model\User;
use app\model\UserBalanceLog;
use Exception;
use think\Db;
use think\facade\Log;
use Wechat\CommerceApp;

class OrderService
{
	/**
	 * 封装数据库订单保存数据
	 *
	 * @param string $order_id
	 * @param string $sku_id
	 * @return array
	 * @throws Exception
	 */
	public static function createOrderSaveData(string $order_id, string $sku_id)
	{
		$save = $info_save = $commission_log = $puser_commission_log = [];

		try {
			//判断订单是否存在
			$order_exist = Order::where('order_id', $order_id)->value('id');
			if ($order_exist) {
				return [$save, $info_save, $commission_log, $puser_commission_log];
			}
			$order_res       = CommerceApp::getInstance()->getOrderInfo($order_id, $sku_id);
			$shop_info       = $order_res['order_detail']['shop_info'] ?? [];
			$product_info    = $order_res['order_detail']['product_info'] ?? [];
			$order_info      = $order_res['order_detail']['order_info'] ?? [];
			$commission_info = $order_res['order_detail']['commission_info'] ?? [];
			$buyer_info      = $order_res['order_detail']['buyer_info'] ?? [];

			Log::error('推客信息：' . json_encode($commission_info, JSON_UNESCAPED_UNICODE));
			Log::error('购买者信息：' . json_encode($buyer_info, JSON_UNESCAPED_UNICODE));
			//获取推客ID
			$sharer_appid = $commission_info['sharer_info']['sharer_appid'] ?? '';
			if (empty($sharer_appid)) {
				Log::error('推客信息不存在：' . json_encode($commission_info, JSON_UNESCAPED_UNICODE));
				return [$save, $info_save, $commission_log, $puser_commission_log];
			}
			$user = User::field('id, parent_user_id, level, agent_id')->where('status', User::STATUS_YES)->where('sharer_appid', $sharer_appid)->find();
			if (empty($user)) {
				Log::error('用户不存在：' . $sharer_appid);
				return [$save, $info_save, $commission_log, $puser_commission_log];
			}
			$user_id  = $user['id'];
			$agent_id = $user['agent_id'] ?? 0;

			//推客机构分佣信息
			$promoter_agency_info = $commission_info['promoter_agency_info'] ?? [];
			if (empty($promoter_agency_info)) {
				Log::error('推客机构分佣信息不存在：' . json_encode($commission_info, JSON_UNESCAPED_UNICODE));
				return [$save, $info_save, $commission_log, $puser_commission_log];
			}

			//获取商品自增ID
			$product_id = $product_info['product_id'];
			$shop_appid = $shop_info['appid'];
			$goods      = Goods::field('id, commission, share_commission, subsidy_commission, partners_subsidy_push, partners_subsidy_shop')->where('product_id', $product_id)->where('shop_appid', $shop_appid)->find();
			if (empty($goods)) {
				Log::error('商品不存在：' . json_encode($product_info, JSON_UNESCAPED_UNICODE));
				return [$save, $info_save, $commission_log, $puser_commission_log];
			}
			$goods_id = $goods['id'];
			//商品售价
			$sale_price = $product_info['actual_payment'];
			//实际佣金（机构佣金）
			$actual_commission = $promoter_agency_info['amount'] ?? 0;

			$is_free = $commission = $share_commission = $subsidy_commission = $one_commission = $agent_commission = $agent_push_commission = $agent_shop_commission = $agent_shop_agent = 0;
			//推客分享赚佣金
			$setting          = AgentDistribution::getLevelInfo($agent_id, $user['level'], 1);
			$agent_ratio      = $setting['agent_ratio']; //合作商佣金比例
			$ratio            = $setting['ratio'] / 100; //推客分享赚佣金比例
			$type             = $setting['type']; //分销类型，0：关闭，1：一级
			$ratio_one        = $setting['ratio_one'] / 100; //一级分销比例
			$share_commission = round($actual_commission * $ratio);

			//判断商品是否0元购
			$free = GoodsFree::where('goods_id', $goods_id)->value('id');
			//如果商品是0元购，则补贴佣金 = 商品售价 - 实际佣金
			if ($free) {
				// TODO 零元购不分佣，那这里是不是有问题？？
				$is_free            = 1;
				$subsidy_commission = $sale_price - $actual_commission;
			} else {
				$subsidy_commission = $goods['subsidy_commission'];
				//如果开启分销，且用户有上级，则一级分销佣金 = 实际佣金 * 一级分销比例
				if ($type && $user['parent_user_id'] > 0 && $ratio_one > 0) {
					$one_commission = round($actual_commission * $ratio_one);
				}
			}
			//直推或自购佣金 = 分享赚佣金 + 补贴佣金
			$commission = $share_commission + $subsidy_commission;
			if ($agent_id && $goods['partners_subsidy_push'] > 0) {
				$agent_push_commission = $goods['partners_subsidy_push'];
			}
			//如果小店在合作商下且有小店补贴佣金，则添加小店补贴佣金
			if ($goods['partners_subsidy_shop'] > 0) {
				$agent_shop_agent      = AgentShop::where('appid', $shop_appid)->value('agent_id');
				$agent_shop_commission += $goods['partners_subsidy_shop'];
			}
			if ($user['agent_id'] > 0) {
				//合作商佣金 = 实际佣金 * 合作商佣金比例 + 补贴推客佣金 + 补贴小店佣金
				$agent_commission = round($actual_commission * $agent_ratio + $agent_push_commission);
			}
			if ($agent_shop_agent > 0 && $agent_shop_agent == $agent_id) {
				$agent_commission += $agent_shop_commission;
			}
			//利润 = 实际佣金 - 推客佣金 - 合作商佣金
			$profit = $actual_commission - $agent_commission - $commission;

			$save      = [
				'user_id'                  => $user_id,
				'agent_id'                 => $agent_id,
				'goods_id'                 => $goods_id,
				'product_id'               => $product_id,
				'shop_appid'               => $shop_appid,
				'order_id'                 => $order_id,
				'sku_id'                   => $sku_id,
				'title'                    => $product_info['title'],
				'image'                    => $product_info['thumb_img'] ?? '',
				'total'                    => $sale_price,
				'actual_commission'        => $actual_commission,
				'commission'               => $commission,
				'share_commission'         => $share_commission,
				'subsidy_commission'       => $subsidy_commission,
				'one_commission'           => $one_commission,
				'agent_commission'         => $agent_commission,
				'agent_subsidy_commission' => $agent_push_commission,
				'agent_shop_commission'    => $agent_shop_commission,
				'agent_shop_agent'         => $agent_shop_agent,
				'profit'                   => $profit,
				'is_free'                  => $is_free,
				'status'                   => $order_info['order_status'],
				'commission_status'        => $order_res['status'],
			];
			$info_save = [
				'shop_info'       => json_encode($shop_info, JSON_UNESCAPED_UNICODE),
				'product_info'    => json_encode($product_info, JSON_UNESCAPED_UNICODE),
				'order_info'      => json_encode($order_id, JSON_UNESCAPED_UNICODE),
				'commission_info' => json_encode($commission_info, JSON_UNESCAPED_UNICODE),
				'buyer_info'      => json_encode($buyer_info, JSON_UNESCAPED_UNICODE),
			];

			$money = round($commission / 100, 2);
			if ($money > 0) {
				$commission_log = [
					'user_id'      => $user_id,
					'from_user_id' => $user_id,
					'type'         => UserBalanceLog::TYPE_NEED_RECEIVE,
					'scene'        => UserBalanceLog::SCENE_SHARE_ORDER,
					'money'        => $money,
					'order_money'  => round($sale_price / 100, 2),
					'order_id'     => $order_id,
				];
			}

			$puser_commission_log = [];
			if ($user['parent_user_id'] > 0) {
				$p_user = User::field('id, parent_user_id, level, agent_id')->where('id', $user['parent_user_id'])->find();
				if (!empty($p_user) && $p_user['level'] >= 2) {
					$config               = Config::where('name', '=', 'real_name')->value('value');
					$puser_commission_log = [
						'user_id'      => $p_user['id'],
						'from_user_id' => $user_id,
						'type'         => UserBalanceLog::TYPE_NEED_RECEIVE,
						'scene'        => UserBalanceLog::SCENE_CREATE_ORDER,
						'money'        => $config,
						'order_money'  => round($sale_price / 100, 2),
						'order_id'     => $order_id,
					];
				}
			}


		} catch (Exception $e) {
			throw new Exception($e->getMessage());
		}
		return [$save, $info_save, $commission_log, $puser_commission_log];
	}

	/**
	 * 更新用户余额
	 *
	 * @param string $order_id
	 * @return bool
	 */
	public static function updateUserBalance(string $order_id)
	{
		$order = Order::where('order_id', $order_id)->find();
		//TODO: 因为非本系统的订单也会有回调，所以如果订单不存在系统，直接完成不需要微信重复发送回调
		if (!$order) {
			Log::error('订单不存在：' . $order_id);
			return true;
		}

		$user = User::field('id, parent_user_id, total, money, agent_id, order_count, rank')
			->where('id', $order['user_id'])
			->where('status', User::STATUS_YES)
			->find();
		if (!$user) {
			Log::error('用户不存在：' . $order['user_id']);
			return false;
		}
		Db::startTrans();

		// 累加订单数量
		$user_res = User::where('id', $user['id'])->update([
			'order_count' => $user['order_count'] + 1,
		]);
//        $parent_user_res = true;
//        //给推客上级用户添加佣金
//        if ($user['parent_user_id'] > 0) {
//            $parent_user = User::field('id, total, money, agent_id')->where('id', $user['parent_user_id'])->find();
//            if ($parent_user) {
//                $parent_user_res = User::where('id', $parent_user['id'])->update([
//                    'total' => $parent_user['total'] + $order['one_commission'],
//                    'money' => $parent_user['money'] + $order['one_commission'],
//                ]);
//            }
//        }

		// 佣金奖励
		$userModel           = new User();
		$UserBalanceLogModel = new UserBalanceLog();
		$balanceLogData      = $UserBalanceLogModel->where(['order_id' => $order_id, 'status' => 20])->select();

		$updateStatusLogIds = [];
		// 将分佣金额加到用户余额
		foreach ($balanceLogData as $value) {
			$updateStatusLogIds[] = $value['log_id'];
			$userModel->setIncMoney($value['user_id'], $value['money'] * 100);
			$userModel->setIncTotal($value['user_id'], $value['money'] * 100);
		}

		// 给用户账户分佣后，将状态改为已结算
		$UserBalanceLogModel->whereIn('log_id', $updateStatusLogIds)->update([
			'status' => UserBalanceLog::STATUS_COMPLETED,
		]);

		// 团队奖励
		$team_ids      = explode('|', trim($user['rank'], '|'));
		$team_ids      = array_reverse(array_slice(array_reverse($team_ids), 0, 9));
		$team_user_ids = $userModel->where('id', 'in', $team_ids)->where('level', '=', 3)->column('id');

		// 获取当前分佣队列开头的数据
		$firstOrderTeamCommissionId = OrderTeamCommissionLogModel::where('user_id', $order['user_id'])
			->where('level', 1)
			->order('id', 'desc')
			->value('id');
		// 获取当前分佣队列数据
		$orderTeamCommissionLogCount = OrderTeamCommissionLogModel::where('user_id', $order['user_id'])
			->where('id', '>=', $firstOrderTeamCommissionId)
			->count();
		$orderTeamCommissionLogCount = intval($orderTeamCommissionLogCount);
		$nextUserId                  = $team_ids[0];
		$level                       = 1;

		if ($orderTeamCommissionLogCount < count($team_ids)) {
			$nextUserId = $team_ids[$orderTeamCommissionLogCount];
			$level      = $orderTeamCommissionLogCount + 1;
		}
		if ($orderTeamCommissionLogCount == count($team_ids)) {
			$nextUserId = 0;
			$level      = $orderTeamCommissionLogCount + 1;
		}

		if (in_array($nextUserId, $team_user_ids)) {
			$setting     = DistributionSetting::getLevelInfo(3, 1);
			$team_reward = round($setting['team_ratio'] * $order['actual_commission'] / 10000, 2);

			if ($team_reward > 0) {
				// 将金额发放到用户余额 && 累计总收益金额
				$userModel->setIncMoney($nextUserId, $team_reward * 100);
				$userModel->setIncTotal($nextUserId, $team_reward * 100);

				// 更新分佣记录信息
				$UserBalanceLogModel->save([
					'order_id'     => $order_id,
					'user_id'      => $nextUserId,
					'from_user_id' => $user['id'],
					'type'         => UserBalanceLog::TYPE_NEED_RECEIVE,
					'scene'        => UserBalanceLog::SCENE_TEAM,
					'money'        => $team_reward,
					'status'       => UserBalanceLog::STATUS_COMPLETED,
				]);

				// 添加订单团队分佣记录表 给系统分佣的话，也需要记录
				OrderTeamCommissionLogModel::create([
					'level'                     => $level,
					'user_id'                   => $order['user_id'],
					'order_id'                  => $order_id,
					'commission_user_id'        => $nextUserId,
					'actual_commission_user_id' => in_array($nextUserId, $team_user_ids) ? $nextUserId : 0,
					'created_at'                => date('Y-m-d H:i:s'),
					'updated_at'                => date('Y-m-d H:i:s'),
				]);
			}
		}

//        // 满足条件时升级v2
//        if ($user['level'] == 1) {
//            $setting     = DistributionSetting::getLevelInfo($user['level'], 1);
//            if ($user['order_count'] + 1 >= $setting['order_count']) {
//                User::where('id', $user['id'])->update(['level' => 2]);
//            }
//        }

		$agent_res = $shop_agent_res = true;
		if ($order['agent_id'] > 0) {
			$agent = AdminAgent::field('id, total_money, money')->where('id', $order['agent_id'])->find();
			//如果小店补贴佣金跟推客所属的合作商不一样，则代理商佣金需要减去小店补贴佣金
			$shop_agent = null;
			if ($order['agent_id'] != $order['agent_shop_agent']) {
				$agent_commission = $order['agent_commission'] - $order['agent_shop_commission'];
				$shop_agent       = AdminAgent::field('id, total_money, money')->where('id', $order['agent_shop_agent'])->find();
			} else {
				$agent_commission = $order['agent_commission'];
			}

			$agent_res = AdminAgent::where('id', $agent['id'])->update([
				'total_money' => $agent['total_money'] + $agent_commission,
				'money'       => $agent['money'] + $agent_commission,
			]);
			if ($shop_agent) {
				$shop_agent_res = AdminAgent::where('id', $order['agent_shop_agent'])->update([
					'total_money' => $shop_agent['total_money'] + $order['agent_shop_commission'],
					'money'       => $shop_agent['money'] + $order['agent_shop_commission'],
				]);
			}
		}
		if ($user_res /*&& $parent_user_res*/ && $agent_res && $shop_agent_res) {
			Db::commit();
			return true;
		}
		Db::rollback();
		return false;
	}
}
